package user

import (
	"api-go/cache"
	"api-go/model"
	"api-go/serializer"
	"api-go/util"
	"bytes"
	"context"
	"fmt"
	"math/rand"
	"text/template"
	"time"
)

var ctx = context.Background()

// 更改密码所需信息
type ChangePassService struct {
	Password string `form:"password" binding:"required,min=6,max=18"`
	Code     string `form:"code" binding:"required,min=6,max=6"`
	Email    string `form:"email" binding:"email"`
}

// 更改密码所需信息
type Email struct {
	Code  string    `form:"code"`
	Email string    `form:"email" binding:"email"`
	Time  time.Time `form:"time"`
	Body  string    `form:"body" binding:"required"`
}

// 邮件html传入参数
type EmailHtml struct {
	Code string
}

//生成随机的6位数验证码
func CodeGenerate() string {
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	vcode := fmt.Sprintf("%06v", rnd.Int31n(1000000))
	fmt.Println(vcode)
	return vcode
}

//发送验证码邮件
func (service *Email) SendEmail() *serializer.Response {
	str := "qt_sentEmail_" + service.Body + "_" + service.Email
	code := CodeGenerate()
	err := cache.RedisClient.Set(ctx, str, code, 5*time.Minute).Err()
	if err != nil {
		return serializer.ErrorResponse(serializer.CodeSendEmailError)
	}
	user := []string{service.Email}
	// //获取项目根目录
	// wd, err := os.Getwd()
	// if err != nil {
	// 	return serializer.ErrorResponse(serializer.CodeSendEmailError)
	// }
	// //读取html文件
	// t, _ := template.ParseFiles(wd + "./service/v1/user/email_html/code.html")
	t, _ := template.ParseFiles("/www/wwwroot/api.qt.music.cn/html/code.html")

	var body bytes.Buffer
	headers := "MIME-version: 1.0;\nContent-Type:text/html"
	body.Write([]byte(fmt.Sprintf("From:轻听官方邮箱\nTo:%s\nSubject:轻听APP系统邮件\n%s\n\n", user[0], headers)))
	t.Execute(&body, EmailHtml{Code: code})
	// username: 用户名
	// 		password: 密码
	// 		host: smtp服务器地址
	// 		to: 填写多个接收者的邮箱
	// 		subject: 主题
	// 		body: 发送的主要信息
	isSend := util.SendEmail(user, body.Bytes())
	if isSend {
		return serializer.OkResponse(&Email{Code: code, Email: service.Email, Time: time.Now(), Body: str})
	} else {
		return serializer.ErrorResponse(serializer.CodeSendEmailError)
	}
}

func (service *ChangePassService) ChangePasswordByEmail() *serializer.Response {
	var user model.User
	var code string
	var isSuccess bool
	str := "qt_sentEmail_changePasswordByEmail_" + service.Email

	if _, err := cache.RedisClient.Exists(ctx, str).Result(); err != nil {
		isSuccess = false
	} else {
		if code, err = cache.RedisClient.Get(ctx, str).Result(); err != nil {
			isSuccess = false
		}
	}
	//判断用户是否存在
	if err := model.DB.Where("email = ?", service.Email).First(&user).Error; err != nil {
		return serializer.ErrorResponse(serializer.CodeUserNotExistError)
	}
	if service.Code == code {
		isSuccess = user.ChangePasswordByEmail(service.Password, service.Email)
	} else {
		isSuccess = false
	}
	fmt.Println(isSuccess)
	if isSuccess {
		//修改完成后删除该验证码
		cache.RedisClient.Del(ctx, str)
		//去掉密码显示
		return serializer.OkResponse(serializer.BuildUserData(&user))
	} else {
		return serializer.ErrorResponse(serializer.CodeChangePasswordError)
	}
}
